Explain the usage of the CASE statement in SQL for conditional expressions.
Explain the usage of the CASE statement in SQL for conditional expressions.
283
04-Jul-2023
Updated on 05-Jul-2023
Aryan Kumar
05-Jul-2023Sure. The CASE statement in SQL is a conditional statement that allows you to evaluate a condition and return a different value depending on the result of the evaluation. The CASE statement can be used to perform a variety of tasks, such as:
The CASE statement has the following syntax:
SQL
The
condition1is the first condition that will be evaluated. If the condition is true, then thevalue1will be returned. If the condition is false, then thecondition2will be evaluated. If thecondition2is true, then thevalue2will be returned. This process will continue until one of the conditions is true, or until theELSEclause is reached. If theELSEclause is reached, then thevalueNwill be returned.The
valueNcan be any expression, including a literal value, a column name, or a function call. ThevalueNcan also be a nested CASE statement.Here is an example of how the CASE statement can be used to format data based on different conditions:
SQL
This query will select the
customer_nameandstatuscolumns from thecustomerstable. TheCASEstatement will be used to format thestatuscolumn based on the value of thestatuscolumn. If the value of thestatuscolumn isActive, then theCASEstatement will return the valueActive. If the value of thestatuscolumn isInactive, then theCASEstatement will return the valueInactive. If the value of thestatuscolumn is notActiveorInactive, then theCASEstatement will return the valueUnknown.Here is an example of how the CASE statement can be used to calculate different values for different groups of data:
SQL
This query will select the
departmentandbonuscolumns from theemployeestable. TheCASEstatement will be used to calculate thebonuscolumn based on the value of thedepartmentcolumn. If the value of thedepartmentcolumn isSales, then theCASEstatement will return the value of thesalarycolumn multiplied by 1.1. If the value of thedepartmentcolumn isMarketing, then theCASEstatement will return the value of thesalarycolumn multiplied by 1.2. If the value of thedepartmentcolumn is notSalesorMarketing, then theCASEstatement will return the value of thesalarycolumn.The CASE statement is a powerful tool that can be used to perform a variety of tasks in SQL. It is a versatile statement that can be used in a variety of ways to analyze data.